package com.situ.gcbs.server.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.situ.gcbs.server.model.Member;
import com.situ.gcbs.server.model.searchbean.MemberSearchBean;
import com.situ.gcbs.server.service.MemberService;
import com.situ.gcbs.server.util.PaginateInfo;
import com.situ.gcbs.server.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能：
 *
 * @author 千堆雪
 * @version 1.0.0
 * @since 2024/5/20
 * <p>
 * created by 千堆雪 on 2024/5/20 15:05, last modified by 千堆雪 on 2024/5/20 15:05
 */
@Controller
@RequestMapping("/excel")
public class ExcelImportExportController {
    private MemberService memberService;

    @Autowired
    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }

    /**
     * 导入出为excel
     */
    @RequestMapping("/export")
    public void export(Integer page, Integer limit, MemberSearchBean msb, HttpServletResponse response) throws Exception {
        if (page == null || page < 1) {
            page = 1;
        }
        if (limit == null || limit < 1) {
            limit = Integer.MAX_VALUE;
        }

        PaginateInfo pi = PaginateInfo.of(page, limit);

        List<Member> members = memberService.findAll(pi, msb);

        //设置必要的响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        //设置导出文件名
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String fileName = URLEncoder.encode("会员列表导出_" + format, StandardCharsets.UTF_8)
                .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), Member.class)
                .sheet("会员列表")
                .doWrite(members);

    }

    /**
     * 从excel文件中导入会员数据
     *
     * @param file 会员模板文件
     */
    @PostMapping("import")
    @ResponseBody
    public Result importFromExcel(MultipartFile file) throws Exception {
        InputStream is = file.getInputStream();
        EasyExcel.read(is, Member.class, new UploadListener(memberService)).sheet().doRead();
        return Result.success();
    }

    //上传监听器
    private static class UploadListener implements ReadListener<Member> {
        private final List<Member> members = new ArrayList<>();
        private final MemberService memberService;

        public UploadListener(MemberService memberService) {
            this.memberService = memberService;
        }

        @Override
        public void invoke(Member member, AnalysisContext analysisContext) {
            members.add(member);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            System.out.println("全部读取结束后执行");
            for (Member member : members) {
                this.memberService.save(member);
            }
        }
    }
}
